# -*- coding: utf-8 -*-
"""
@ Created on 2024-06-14 12:23
---------
@summary: 日志模块
---------
@author: Lsaiah
"""

import logging
import os
import sys
from datetime import datetime
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler

# 创建日志目录
LOG_DIR = "logs"
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)

# 日志格式
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

# 创建根日志记录器
logger = logging.getLogger("fastapi_admin")
logger.setLevel(logging.INFO)

# 避免重复添加处理器
if not logger.handlers:
    # 控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.INFO)
    console_formatter = logging.Formatter(LOG_FORMAT, LOG_DATE_FORMAT)
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)

    # 文件处理器 - 按大小轮转
    file_handler = RotatingFileHandler(
        os.path.join(LOG_DIR, "app.log"),
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=5,
        encoding="utf-8"
    )
    file_handler.setLevel(logging.INFO)
    file_formatter = logging.Formatter(LOG_FORMAT, LOG_DATE_FORMAT)
    file_handler.setFormatter(file_formatter)
    logger.addHandler(file_handler)

    # 错误日志处理器 - 按时间轮转
    error_handler = TimedRotatingFileHandler(
        os.path.join(LOG_DIR, "error.log"),
        when="midnight",
        interval=1,
        backupCount=30,
        encoding="utf-8"
    )
    error_handler.setLevel(logging.ERROR)
    error_formatter = logging.Formatter(LOG_FORMAT, LOG_DATE_FORMAT)
    error_handler.setFormatter(error_formatter)
    logger.addHandler(error_handler)

# 创建特定模块的日志记录器
def get_logger(name: str) -> logging.Logger:
    """获取指定名称的日志记录器"""
    return logging.getLogger(f"fastapi_admin.{name}")


# 日志装饰器
def log_function_call(func):
    """记录函数调用的装饰器"""
    def wrapper(*args, **kwargs):
        logger.info(f"调用函数: {func.__name__}")
        try:
            result = func(*args, **kwargs)
            logger.info(f"函数 {func.__name__} 执行成功")
            return result
        except Exception as e:
            logger.error(f"函数 {func.__name__} 执行失败: {str(e)}")
            raise
    return wrapper


# 异常日志记录
def log_exception(e: Exception, context: str = ""):
    """记录异常信息"""
    logger.error(f"异常信息 [{context}]: {str(e)}", exc_info=True)


# 请求日志记录
def log_request(method: str, url: str, status_code: int, response_time: float):
    """记录HTTP请求信息"""
    logger.info(f"HTTP {method} {url} - {status_code} - {response_time:.3f}s")


# 数据库操作日志
def log_db_operation(operation: str, table: str, success: bool, error: str = None):
    """记录数据库操作"""
    if success:
        logger.info(f"数据库操作成功: {operation} on {table}")
    else:
        logger.error(f"数据库操作失败: {operation} on {table} - {error}")


# 用户操作日志
def log_user_action(user_id: int, action: str, details: str = ""):
    """记录用户操作"""
    logger.info(f"用户操作: User[{user_id}] - {action} - {details}")


# 安全事件日志
def log_security_event(event_type: str, details: str, ip_address: str = ""):
    """记录安全事件"""
    logger.warning(f"安全事件: {event_type} - {details} - IP: {ip_address}")


# 性能监控日志
def log_performance(operation: str, duration: float, details: str = ""):
    """记录性能信息"""
    if duration > 1.0:  # 超过1秒的操作记录为警告
        logger.warning(f"性能警告: {operation} 耗时 {duration:.3f}s - {details}")
    else:
        logger.info(f"性能信息: {operation} 耗时 {duration:.3f}s - {details}")


__all__ = [
    "logger", "get_logger", "log_function_call", "log_exception",
    "log_request", "log_db_operation", "log_user_action",
    "log_security_event", "log_performance"
]
